#!/bin/bash

action=$1
TMP_RES=$2
webPort=6080
# vncPort 由系统决定，但默认是5904
# vncPort


if [ "$action" == "" ]; then
	action=stop
fi

if [ "$TMP_RES" == "" ]; then
	TMP_RES=1920x1080
fi


command -v Xtigervnc
rltvnc=$?

[ -x /usr/bin/websockify ]
rltweb=$?

if [ $rltvnc -ne 0 ] || [ $rltweb -ne 0 ]; then
	cat <<- EOF > /tmp/msg.txt

		webvnc 未安装，请先安装！

		安装步骤为：
		1). 在桌面上打开软件管家
		2). 在软件管家主界面，点击左侧的 “系统” 按钮
		3). 然后翻找 “webvnc” 软件包并安装好

	EOF
	gxmessage -title "VNC远程控制" -file /tmp/msg.txt -center
	exit 1
fi

mkdir -p /etc/webvnc/ 2>/dev/null

function show_web_msg() {
	cat <<- EOF > /tmp/ip.txt

		通过浏览器控制此模拟器
		================================
		请在同一wifi下的电脑或手机上用网页浏览器访问以下地址:

	EOF

	/exbin/tools/vm_ip2link.sh "http://" ":${webPort}">>/tmp/ip.txt

	gxmessage -title "VNC远程控制" -file /tmp/ip.txt -center
}

case "${action}" in
	"start")
		command -v webvnc
		if [ $? -eq 0 ]; then
			# 旧版的启动文件，不要了
			rm -rf /home/droidvm/Desktop/webvnc.desktop
			rm -rf /usr/share/applications/webvnc.desktop
			gxmessage -title "web远程控制" "webvnc已经有更新，请重新安装webvnc!"  -center
			exit 1
		fi

		if [ "${vncPort}" != "" ]; then exit 0; fi
		cp -f ${DirGuiConf}/xserver_order.txt /etc/webvnc/xserver_order.txt
		echo "Xtigervnc xlorie Xvfb">${DirGuiConf}/xserver_order.txt
		reboot
		;;
	"stop")
		if [ -f /etc/webvnc/xserver_order.txt ]; then
			cp -f /etc/webvnc/xserver_order.txt ${DirGuiConf}/xserver_order.txt
		else
			echo "Xvfb xlorie Xtigervnc">${DirGuiConf}/xserver_order.txt
		fi
		reboot
		;;
	"webon")
		if [ "${vncPort}" == "" ]; then
			gxmessage -title "web远程控制" "VNC服务端未启动，无法转发到网页端进行控制"  -center
			exit 1
		fi
		/usr/bin/websockify --web /usr/share/novnc/utils/../ ${webPort} localhost:${vncPort} &
		show_web_msg
		;;
	"weboff")
		pkill websockify
		;;
	"setres")
		resw=`echo "$TMP_RES"|awk -v FS="x" '{print $1}'`
		resh=`echo "$TMP_RES"|awk -v FS="x" '{print $2}'`
		if [ "$resw" == "" ]; then resw=1920; fi
		if [ "$resh" == "" ]; then resh=1080; fi
		startx vmScreenSizeReq  $resw $resh
		echo "$TMP_RES" > /etc/webvnc/last_res.rc
		;;
	"setpasswd")
		cmd -e "vncpasswd /etc/webvnc/password.data"
		;;
	*)
		# ~/.vnc/ 中的日志文件非常占空间！！！
		rm -rf $HOME/.vnc/*.log
		;;
esac

